<?php

namespace App\Http;

use App\Models\ApiFilter\ApiFilterBase;
use App\Models\Traits\PublicId;
use Illuminate\Support\Facades\Log;

class ApiResponse
{
    private $controller;

    /**
     * ApiResponse constructor.
     *
     * @param $controller
     */
    public function __construct($controller)
    {
        // return $this->apiResponse->success();
        $this->controller = $controller;
        if (Request()->header('sql') === 'goodTime') {
            sql(false);
        }
    }

    /**
     * API 返回JSON
     *
     * @param [any] $data 返回的数据
     * @param [string] $msg 状态描述
     * @param [integer] $code 状态码
     * @param [array|string|null] $model array or "model:modelName"
     */
    public function success($data = [], $msg = 'ok', $code = 200, $model = null)
    {
        if ($model) {
            $filter = new ApiFilterBase();

            try {
                $data = $filter->filterData($data, $model);
            } catch (\Exception $e) {
                Log::error(
                    '[ApiResponse] filterData error',
                    [
                        'messages' => $e->getMessage() . '::' . json_encode(Request()->all()),
                        'code' => $e->getCode(),
                        'file' => $e->getFile(),
                        'line' => $e->getLine(),
                    ]
                );
            }

        }

        if (Request()->header('sql') === 'goodTime') {
            $data['sql'] = $_SERVER['sql'];
        }

        $msg = $msg ?? 'ok';
        $code = $code ?? 200;

        if ($_SERVER['debug_out'] && config('app.debug')) {
            header('debug-xx:' . $_SERVER['debug_out']);
        }
        // 在此处调用id加密过滤，对$data
        return response(json_encode([
            'code' => $code,
            'msg' => $msg,
            'data' => $this->encodeData($data)
        ]), $code)->header('Content-type', 'application/json')
            ->header('debug-cookie', session()->getId());
    }

    /**
     * API 返回错误
     *
     * @param [string] $msg 状态描述
     * @param [integer] $code 状态码
     */
    public function error($msg = 'error', $code = 400, $data = [])
    {
        $msg = $msg ?? 'error';
        $code = $code ?? 401;

        if (Request()->header('sql') === 'goodTime') {
            $data['sql'] = $_SERVER['sql'];
        }
        // 在此处调用id加密过滤，对$data
        return response(json_encode([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]), $code)->header('Content-type', 'application/json');
    }

    /**
     * API 返回JSON
     *
     * @param [any] $data 返回的数据
     * @param [string] $msg 状态描述
     * @param [integer] $code 状态码
     * @param [array|string|null] $model array or "model:modelName"
     */
    public function success1($data = [], $msg = 'ok', $code = 200, $model = null)
    {
        if ($model) {
            $filter = new ApiFilterBase();
            try {
                $data = $filter->filterData($data, $model);
            } catch (\Exception $e) {
                Log::error(
                    '[ApiResponse] filterData error',
                    [
                        'messages' => $e->getMessage() . '::' . json_encode(Request()->all()),
                        'code' => $e->getCode(),
                        'file' => $e->getFile(),
                        'line' => $e->getLine(),
                    ]
                );
            }
        }
        if (Request()->header('sql') === 'goodTime') {
            $data['sql'] = $_SERVER['sql'];
        }
        $msg = $msg ?? 'ok';
        $code = $code ?? 200;

        if ($_SERVER['debug_out'] && config('app.debug')) {
            header('debug-xx:' . $_SERVER['debug_out']);
        }
        // 在此处调用id加密过滤，对$data
        return response(json_encode([
            'status' => $code,
            'message' => $msg,
            'data' => $this->encodeData($data)
        ]), $code)->header('Content-type', 'application/json')
            ->header('debug-cookie', session()->getId());
    }

    /**
     * 过滤多层数据结构，将id加密处理
     *
     * @param [any] $data
     *
     * @return mixed [any]
     */
    public function encodeData($data)
    {
        /*
        if (is_object($data)) {
            if (method_exists($data, 'toArray')) {
                $data = $data->toArray();
            } else {
                $data = (array)$data;
            }
        }
        $type = gettype($data);
        if ($type === 'array' || $type === 'object') {
            foreach ($data as $k => $v) {
                $vType = gettype($v);

                if ($vType === 'integer') {
                    if (preg_match('/id$/i', $k)) {
                        $data[$k] = $this->encodeDataId($v);
                    }
                } elseif (in_array($vType, array('array', 'object'))) {
                    $data[$k] = $this->encodeData($v);
                }
            }
            return $data;
        }
        */

        return $data;
    }

    /**
     * @param $id
     *
     * @return int|mixed|string|null
     */
    public function encodeDataId($id)
    {
        /*
        if (!is_integer($id)) {
            return $id;
        }
        $idString = PublicId::encodePublicId($id);
        if (strlen($idString) < env('HASHIDS_MAIN_LENGTH')) {
            $idString = $id;
        }
        */
        return $id;
    }
}
